package com.zhouixi.ras_js_java.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhouixi.ras_js_java.utils.RetResponse;
import com.zhouixi.ras_js_java.utils.RetResult;
import com.zhouixi.ras_js_java.utils.SecurityUtil;

import cn.hutool.crypto.asymmetric.RSA;

@Controller
public class WebController {
	
	private final static Logger log = LoggerFactory.getLogger(WebController.class);
	
	

	private final static String publicKey = "PUBLIC_KEY";
	private final static String privateKey = "PRIVATE_KEY";
	
	@RequestMapping("/index")
	public String index() {
		return "index";
	}
	
	@RequestMapping("/decrypt")
	@ResponseBody
	public RetResult decrypt(byte [] encrypt) throws Exception {
		File file = ResourceUtils.getFile("classpath:keys/secret_key.txt");
		Properties pro = new Properties();//创建集合
		pro.load(new FileInputStream(file));
		
		System.out.println("PUBLIC_KEY"+pro.get("PRIVATE_KEY"));
		System.out.println("PRIVATE_KEY"+pro.get("PUBLIC_KEY"));
		
		String decryptRSADefault = SecurityUtil.decryptRSADefault(pro.get("PRIVATE_KEY").toString(), new String(encrypt,"UTF-8"));
		System.out.println("解密："+decryptRSADefault);
		return RetResponse.makeOKRsp();
	}
	
	@ResponseBody
	@RequestMapping("/getPulbicKey")
	public String getPublicKey() throws IOException {
		RSA rsa = new RSA();
		//Resource resource = new ClassPathResource("keys/secret_key.txt");
		File file = ResourceUtils.getFile("classpath:keys/secret_key.txt");
		Properties pro = new Properties();//创建集合
		FileOutputStream out = null ;
		try {
	        pro.setProperty(privateKey, rsa.getPrivateKeyBase64());
	        pro.setProperty(publicKey, rsa.getPublicKeyBase64());
	        out = new FileOutputStream(file);
	        pro.store(out,"密钥");
	        out.flush();
	        
		} catch (Exception e) {
			log.error("流异常：：：{}", e );
		} finally {
			pro.clear();
			if(out != null ) {
				try {
					out.close();
				} catch (IOException e) {
					log.error("流异常",e);
				}
			}
		}
		return rsa.getPublicKeyBase64() ;
	}
	
}
